package com.zky.gulimall.ssoclient.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description hello
 * @Author 张开源
 * @Date 2022/11/30 21:29
 * @Version 1.0
 **/
@Controller
@Slf4j
public class HelloController {
    @Value("${sso.server.url}")
    private String serverUrl;

    /**
     * 无需登录
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * @param model
     * @param token   跳转带来的token
     * @param session
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, @RequestParam(value = "token", required = false) String token, HttpSession session) {
        if (!StringUtils.isEmpty(token)) {
            //去认证中心去取
            RestTemplate template = new RestTemplate();
            ResponseEntity<String> entity = template.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
            if (entity.getStatusCodeValue() == 200) {
                session.setAttribute("loginUser", entity.getBody());
            } else {
                log.error("result:" + entity.getStatusCodeValue());
            }
        }
        Object attribute = session.getAttribute("loginUser");
        if (Objects.isNull(attribute)) {
            //未登录,返回登录页
            log.warn("login fail ,will redirect to login: " + serverUrl);
            return "redirect:" + serverUrl + "?redirect_url=http://client1.com:8081/employees";
        }
        List<String> em = new ArrayList<>();
        em.add("张三");
        em.add("王小二");
        em.add("王大二");
        em.add("王刘二");
        model.addAttribute("emps", em);
        return "list";
    }
}
